(function () {
    let lastTime = 0;
    let vendors = ['webkit', 'moz'];
    for (let x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
        window.cancelAnimationFrame =
            window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function (callback, element) {
            let currTime = new Date().getTime();
            let timeToCall = Math.max(0, 16 - (currTime - lastTime));
            let id = window.setTimeout(function () { callback(currTime + timeToCall); },
                timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function (id) {
            clearTimeout(id);
        };
}());

(function () {
    let Snowfall = function (element, opts) {
        let defaults = {
            flakeCount: 35,
            flakeColor: '#ffffff',
            flakeIndex: 999999,
            minSize: 1,
            maxSize: 2,
            minSpeed: 1,
            maxSpeed: 5,
            round: false,
            shadow: false,
            collection: false,
            collectionHeight: 40,
            deviceorientation: false
        },
            options = { ...defaults, ...opts },
            random = function random(min, max) {
                return Math.round(min + Math.random() * (max - min));
            };

        if (!element.data) {
            element.data = {}
        }
        element.data.snowfall = this;
        let canvasCollection = []

        function Flake(_x, _y, _size, _speed, _id) {
            this.id = _id;
            this.x = _x;
            this.y = _y;
            this.size = _size;
            this.speed = _speed;
            this.step = 0;
            this.stepSize = random(1, 10) / 100;

            if (options.collection) {
                this.target = canvasCollection[random(0, canvasCollection.length - 1)];
            }

            let flakeMarkup = null;

            if (options.image) {
                flakeMarkup = document.createElement("img");
                flakeMarkup.src = options.image;
            } else {
                flakeMarkup = document.createElement("div");
                flakeMarkup.style.background = options.flakeColor;
            }
            let attrs = { 'class': 'snowfall-flakes', 'id': 'flake-' + this.id }
            let style = { 'width': `${this.size}px`, 'height': `${this.size}px`, 'position': 'absolute', 'top': this.y, 'left': this.x, 'fontSize': 0, 'zIndex': options.flakeIndex }
            for (const key in attrs) flakeMarkup.setAttribute(key, attrs[key]);
            for (const key in style) flakeMarkup.style[key] = style[key];

            if (element.tagName === document.tagName) element = document.body;
            element.append(flakeMarkup);

            this.element = document.getElementById('flake-' + this.id);

            // Update function, used to update the snow flakes, and checks current snowflake against bounds
            this.update = function () {
                this.y += this.speed;

                if (this.y > (elHeight) - (this.size + 6)) {
                    this.reset();
                }

                this.element.style.top = this.y + 'px';
                this.element.style.left = this.x + 'px';

                this.step += this.stepSize;

                if (doRatio === false) {
                    this.x += Math.cos(this.step);
                } else {
                    this.x += (doRatio + Math.cos(this.step));
                }

                // Pileup check
                if (options.collection) {
                    let canvas = this.target.element,
                        parentBounds = canvas.data.parent.getBoundingClientRect();
                    canvas.style.width = parentBounds.width + 'px';
                    canvas.style.left = parentBounds.left + 'px';
                    if (this.x > this.target.x && this.x < this.target.width + this.target.x && this.y > this.target.y && this.y < this.target.height + this.target.y) {
                        let ctx = canvas.getContext("2d"),
                            curX = this.x - this.target.x,
                            curY = this.y - this.target.y,
                            colData = this.target.colData;
                        if (colData[parseInt(curX)][parseInt(curY + this.speed + this.size)] !== undefined || curY + this.speed + this.size > this.target.height) {
                            if (curY + this.speed + this.size > this.target.height) {
                                while (curY + this.speed + this.size > this.target.height && this.speed > 0) {
                                    this.speed *= .5;
                                }

                                ctx.fillStyle = "#fff";

                                if (colData[parseInt(curX)][parseInt(curY + this.speed + this.size)] == undefined) {
                                    colData[parseInt(curX)][parseInt(curY + this.speed + this.size)] = 1;
                                    ctx.fillRect(curX, (curY) + this.speed + this.size, this.size, this.size);
                                } else {
                                    colData[parseInt(curX)][parseInt(curY + this.speed)] = 1;
                                    ctx.fillRect(curX, curY + this.speed, this.size, this.size);
                                }
                                this.reset();
                            } else {
                                // flow to the sides
                                this.speed = 1;
                                this.stepSize = 0;

                                if (parseInt(curX) + 1 < this.target.width && colData[parseInt(curX) + 1][parseInt(curY) + 1] == undefined) {
                                    // go left
                                    this.x++;
                                } else if (parseInt(curX) - 1 > 0 && colData[parseInt(curX) - 1][parseInt(curY) + 1] == undefined) {
                                    // go right
                                    this.x--;
                                } else {
                                    //stop
                                    ctx.fillRect(curX, curY, this.size, this.size);
                                    colData[parseInt(curX)][parseInt(curY)] = 1;
                                    this.reset();
                                }
                            }
                        }
                    }
                }

                if (this.x > (elWidth) - widthOffset || this.x < widthOffset) {
                    this.reset();
                }
            }

            // Resets the snowflake once it reaches one of the bounds set
            this.reset = function () {
                this.y = 0;
                this.x = random(widthOffset, elWidth - widthOffset);
                this.stepSize = random(1, 10) / 100;
                this.size = random((options.minSize * 100), (options.maxSize * 100)) / 100;
                this.speed = random(options.minSpeed, options.maxSpeed);
            }
        }

        // local vars
        let flakes = [],
            flakeId = 0,
            i = 0,
            elHeight = element.clientHeight,
            elWidth = element.clientWidth,
            widthOffset = 0,
            snowTimeout = 0;

        // Collection Piece ******************************
        if (options.collection !== false) {
            let testElem = document.createElement('canvas');
            if (!!(testElem.getContext && testElem.getContext('2d'))) {
                let elements = document.querySelectorAll(options.collection),
                    collectionHeight = options.collectionHeight;

                for (let i = 0; i < elements.length; i++) {
                    let bounds = elements[i].getBoundingClientRect(),
                        canvas = document.createElement('canvas'),
                        collisionData = [],
                        ctx = canvas.getContext('2d');
                    canvas.data = {}

                    if (bounds.top - collectionHeight > 0) {
                        document.body.appendChild(canvas);
                        canvas.style.position = 'absolute';
                        canvas.height = collectionHeight;
                        canvas.width = bounds.width;
                        canvas.style.left = bounds.left + 'px';
                        canvas.style.top = bounds.top - collectionHeight + 'px';
                        canvas.data.parent = elements[i];

                        for (let w = 0; w < bounds.width; w++) {
                            collisionData[w] = [];
                        }

                        if (options.image) {
                            const img = new Image();
                            img.src = options.image;
                            img.onload = function () {
                                const pattern = ctx.createPattern(img, 'repeat');
                                ctx.fillStyle = pattern;
                            }
                        } else {
                            ctx.fillStyle = "#fff";
                        }

                        canvasCollection.push({ element: canvas, x: bounds.left, y: bounds.top - collectionHeight, width: bounds.width, height: collectionHeight, colData: collisionData });
                    }
                }
            } else {
                // Canvas element isnt supported
                options.collection = false;
            }
        }
        // ************************************************

        // This will reduce the horizontal scroll bar from displaying, when the effect is applied to the whole page
        if (element.tagName === document.tagName) {
            widthOffset = 25;
        }

        // Bind the window resize event so we can get the innerHeight again
        window.addEventListener("resize", function () {
            elHeight = element.clientHeight;
            elWidth = element.offsetWidth;
            console.log(elHeight);
        });

        // initialize the flakes
        for (i = 0; i < options.flakeCount; i += 1) {
            flakeId = flakes.length;
            flakes.push(new Flake(random(widthOffset, elWidth - widthOffset), random(0, elHeight), random((options.minSize * 100), (options.maxSize * 100)) / 100, random(options.minSpeed, options.maxSpeed), flakeId));
        }

        // This adds the style to make the snowflakes round via border radius property 
        if (options.round) {
            let style = { '-moz-border-radius': options.maxSize, '-webkit-border-radius': options.maxSize, 'border-radius': options.maxSize }
            document.querySelectorAll('.snowfall-flakes').forEach(elem => {
                for (const key in style) {
                    elem.setAttribute(key, attributes[key]);
                }
            });
        }

        // This adds shadows just below the snowflake so they pop a bit on lighter colored web pages
        if (options.shadow) {
            let style = { '-moz-box-shadow': '1px 1px 1px #555', '-webkit-box-shadow': '1px 1px 1px #555', 'box-shadow': '1px 1px 1px #555' }
            document.querySelectorAll('.snowfall-flakes').forEach(elem => {
                for (const key in style) {
                    elem.setAttribute(key, attributes[key]);
                }
            });
        }

        // On newer Macbooks Snowflakes will fall based on deviceorientation
        let doRatio = false;
        if (options.deviceorientation) {
            window.addEventListener('deviceorientation', function (event) {
                doRatio = event.originalEvent.gamma * 0.1;
            });
        }

        // this controls flow of the updating snow
        function snow() {
            for (let i = 0; i < flakes.length; i += 1) {
                flakes[i].update();
            }

            snowTimeout = requestAnimationFrame(function () { snow() });
        }

        snow();

        // clears the snowflakes
        this.clear = function (element) {
            element.querySelectorAll('.snowfall-flakes').forEach(elem => elem.remove());
            flakes = [];
            cancelAnimationFrame(snowTimeout);
        }
    };

    // Initialize the options and the plugin
    // NodeList.prototype.snowfall = function (options) {
    //     for (let i = 0; i < this.length; i++) {
    //         const element = this[i];
    //         if (typeof options === "object" || options === undefined) {
    //             new Snowfall(element, options);
    //         } else if (typeof options === "string") {
    //             if (element.data.snowfall) {
    //                 element.data.snowfall.clear(element);
    //             }
    //         }
    //     }
    // }

    // Node.prototype.snowfall = function (options) {
    //     this.snowfall(options);
    //     return this;
    // }
    Node.prototype.snowfall = function (options) {
        options = options || {}

        if (typeof options === 'string' && this.data?.snowfall) {
            this.data.snowfall.clear(this);
            return this;
        }

        new Snowfall(this, options)

        return this;
    }

    NodeList.prototype.snowfall = function (options) {
        this.forEach(el => el.snowfall(options));
    }
})();